package com.hanxiaozhang.threadbase1ndedition.no10threadpool;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 〈一句话功能简述〉<br>
 * 〈ParallelStream底层使用ForkJoinPool〉
 *
 * @author hanxinghua
 * @create 2021/11/27
 * @since 1.0.0
 */
public class No14ParallelStreamUseForkJoinPool {

    public static void main(String[] args) {

        List<Integer> nums = new ArrayList<>();
        Random r = new Random();
        for (int i = 0; i < 10000; i++) {
            nums.add(1000000 + r.nextInt(1000000));
        }

        long start = System.currentTimeMillis();
        nums.forEach(v -> isPrime(v));
        long end = System.currentTimeMillis();
        System.out.println("使用循环时间: " + (end - start));

        start = System.currentTimeMillis();
        nums.parallelStream().forEach(No14ParallelStreamUseForkJoinPool::isPrime);
        end = System.currentTimeMillis();

        System.out.println("使用parallelStream时间: " + (end - start));
    }

    /**
     * 判断是不是质数
     *
     * @param num
     * @return
     */
    private static boolean isPrime(int num) {
        for (int i = 2; i <= num / 2; i++) {
            if (num % i == 0) {
                return false;
            }
        }
        return true;
    }
}
